using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using AutoMapper;
using UwinEducation.Application.Common.Interfaces.Orders;
using UwinEducation.Application.Dtos.Orders;
using UwinEducation.Application.Dtos;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Shared.Enums;
using UwinEducation.Shared.Models;

namespace UwinEducation.Application.Services.Orders
{
    /// <summary>
    /// 订单服务实现
    /// </summary>
    public class OrderService : IOrderService
    {
        private readonly IOrderRepository _orderRepository;
        private readonly IStudentRepository _studentRepository;
        private readonly IOrderDetailRepository _orderDetailRepository;
        private readonly IOrderDiscountRepository _orderDiscountRepository;
        private readonly IOrderPaymentRepository _orderPaymentRepository;
        private readonly IAppointmentRepository _appointmentRepository;
        private readonly IMapper _mapper;

        public OrderService(
            IOrderRepository orderRepository,
            IStudentRepository studentRepository,
            IOrderDetailRepository orderDetailRepository,
            IOrderDiscountRepository orderDiscountRepository,
            IOrderPaymentRepository orderPaymentRepository,
            IAppointmentRepository appointmentRepository,
            IMapper mapper
        )
        {
            _orderRepository = orderRepository;
            _studentRepository = studentRepository;
            _orderDetailRepository = orderDetailRepository;
            _orderDiscountRepository = orderDiscountRepository;
            _orderPaymentRepository = orderPaymentRepository;
            _appointmentRepository = appointmentRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取订单
        /// </summary>
        public async Task<OrderDto> GetOrderByIdAsync(Guid id)
        {
            var order = await _orderRepository.GetByIdAsync(id);
            if (order == null)
            {
                throw new ArgumentException($"订单不存在: {id}");
            }
            return _mapper.Map<OrderDto>(order);
        }

        /// <summary>
        /// 根据订单编号获取订单
        /// </summary>
        public async Task<OrderDto> GetOrderByNumberAsync(string orderNumber)
        {
            var order = await _orderRepository.GetByOrderNumberAsync(orderNumber);
            return _mapper.Map<OrderDto>(order);
        }

        /// <summary>
        /// 获取学生的订单列表
        /// </summary>
        public async Task<List<OrderDto>> GetStudentOrdersAsync(Guid studentId)
        {
            var orders = await _orderRepository.GetByStudentIdAsync(studentId);
            return _mapper.Map<List<OrderDto>>(orders);
        }

        /// <summary>
        /// 根据支付状态获取订单列表
        /// </summary>
        public async Task<List<OrderDto>> GetOrdersByPaymentStatusAsync(PaymentStatus paymentStatus)
        {
            var orders = await _orderRepository.GetByPaymentStatusAsync(paymentStatus);
            return _mapper.Map<List<OrderDto>>(orders);
        }

        /// <summary>
        /// 获取订单分页列表
        /// </summary>
        public async Task<PagedResult<OrderDto>> GetPagedListAsync(OrderPageRequest pageRequest)
        {
            // 1. 获取分页数据
            var pagedResult = await _orderRepository.GetPagedListAsync(pageRequest);

            return new PagedResult<OrderDto>
            {
                Total = pagedResult.Total,
                Items = _mapper.Map<List<OrderDto>>(pagedResult.Items)
            };
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        public async Task<OrderDto> CreateOrderAsync(CreateOrderDto createOrderDto)
        {
            // 检查订单编号是否已存在
            var existingOrder = await _orderRepository.GetByOrderNumberAsync(
                createOrderDto.OrderNumber
            );
            if (existingOrder != null)
            {
                throw new ArgumentException($"订单编号已存在: {createOrderDto.OrderNumber}");
            }
            // 检查学生是否存在
            var student = await _studentRepository.GetByIdAsync(createOrderDto.StudentId);
            if (student == null)
            {
                throw new ArgumentException($"学生不存在: {createOrderDto.StudentId}");
            }

            // 检查学期开始时间和结束时间同一个学生是否存在
            var _existingOrder = await _orderRepository.GetByStudentIdAndSemesterAsync(
                createOrderDto.StudentId,
                createOrderDto.SemesterStartDate,
                createOrderDto.SemesterEndDate
            );
            if (_existingOrder != null)
            {
                throw new ArgumentException($"{student.Name}:同一学期已经存在订单");
            }

            var order = Order.Create(
                createOrderDto.StudentId,
                createOrderDto.OrderNumber,
                createOrderDto.Description ?? string.Empty,
                createOrderDto.CreatedDate
            );
            await _orderRepository.AddAsync(order);
            return _mapper.Map<OrderDto>(order);
        }

        /// <summary>
        /// 更新订单
        /// </summary>
        public async Task<OrderDto> UpdateOrderAsync(OrderDto orderDto)
        {
            var order = _mapper.Map<Order>(orderDto);
            await _orderRepository.UpdateAsync(order);
            return _mapper.Map<OrderDto>(order);
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        public async Task DeleteOrderAsync(Guid id)
        {
            // 检查订单是否存在
            var order = await _orderRepository.GetByIdAsync(id);
            if (order == null)
            {
                throw new ArgumentException($"订单不存在: {id}");
            }
            // 检查订单明细是否存在数据
            var orderDetails = await _orderDetailRepository.GetByOrderIdAsync(id);
            if (orderDetails.Count > 0)
            {
                throw new ArgumentException($"订单明细存在数据，不能删除: {order.OrderNumber}");
            }
            // 检查订单折扣是否存在数据
            var orderDiscounts = await _orderDiscountRepository.GetByOrderIdAsync(id);
            if (orderDiscounts.Count > 0)
            {
                throw new ArgumentException($"订单折扣存在数据，不能删除: {order.OrderNumber}");
            }
            // 检查订单支付记录是否存在数据
            var orderPayments = await _orderPaymentRepository.GetByOrderIdAsync(id);
            if (orderPayments.Count > 0)
            {
                throw new ArgumentException($"订单支付记录存在数据，不能删除: {order.OrderNumber}");
            }
            //检查学生预约是否存在数据
            var studentSchedules = await _appointmentRepository.GetByOrderIdAsync(id);
            if (studentSchedules.Count > 0)
            {
                throw new ArgumentException($"学生预约存在数据，不能删除: {order.OrderNumber}");
            }

            // 删除订单
            await _orderRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 更新订单支付状态
        /// </summary>
        public async Task UpdatePaymentStatusAsync(Guid orderId, PaymentStatus paymentStatus)
        {
            var order = await _orderRepository.GetByIdAsync(orderId);
            if (order != null)
            {
                order.PaymentStatus = paymentStatus;
                await _orderRepository.UpdateAsync(order);
            }
        }
    }
}